package com.lms.zookeeper;

import org.apache.zookeeper.*;
import java.io.IOException;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-08-21 08:29
 * @Description:
 */
public class DistributedServer {
    private static final String CONNECTION_STRING = "192.168.189.100:2181,192.168.189.101:2181,192.168.189.102:2181";
    private static final int SESSION_TIMEOUT = 2000;
    private ZooKeeper zk = null;


    /**
     * @Author 李孟帅
     * @Description 获取客户端连接
     * @Date 2020/8/20
     **/
    public void getConnection() throws IOException {
        zk = new ZooKeeper(CONNECTION_STRING, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event);

            }
        });
    }

    /**
     * @Author 李孟帅
     * @Description 注册
     * @Date 2020/8/21
     **/
    public void registryServer(String hostname) throws KeeperException, InterruptedException {
        String create = zk.create("/servers/"+hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println(hostname + " is online ," + create);

    }

    /**
    * @Author 李孟帅
    * @Description 业务功能
    * @Date 2020/8/21 
    **/
    public void handleBusiness(String hostname) throws InterruptedException {
        System.out.println(hostname+" start working...");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

        //获取zk连接
        DistributedServer distributedServer = new DistributedServer();
        distributedServer.getConnection();
        //利用zk注册服务器信息
        distributedServer.registryServer(args[0]);
        //启动业务功能
        distributedServer.handleBusiness(args[0]);

    }
}
